#!/usr/bin/env python
# -- coding=utf-8 --


from tornado import web, ioloop, httpclient, httpserver
from tornado.options import define, parse_command_line, options

import urllib, json

define(name="port", default=8000, type=int, help="server port")


class IndexHandler(web.RequestHandler):
    @web.asynchronous
    def get(self):
        query = self.get_argument('q')
        client = httpclient.AsyncHTTPClient()
        client.fetch(
            "https://api.douban.com/v2/book/search?" + urllib.parse.urlencode({"q": query, "start": 0}),
            callback=self.on_response)


def on_response(self, response):
    body = json.loads(response.body.decode('utf-8'))
    print(body)
    self.write(body)
    self.finish()


def main():
    parse_command_line()
    app = web.Application(handlers=[
        (r"^/$", IndexHandler)
    ],
        debug=True
    )
    http_server = httpserver.HTTPServer(app)
    http_server.listen(options.port)
    ioloop.IOLoop.current().start()


if __name__ == '__main__':
    main()
